//
//  Reachability+RAC.swift
//  Panku
//
//  Created by mac on 2017/4/18.
//  Copyright © 2017年 Monster. All rights reserved.
//

import Foundation
import ReactiveCocoa
import ReactiveSwift
import Result
import Reachability

extension Reachability {
    
    //singleton for internet instance
    static let sharedInstanceForInternet = Reachability.forInternetConnection()
    //singleton for WIFI instance
    static let sharedInstanceForWIFI = Reachability.forLocalWiFi()
    
    //signale for internet state change
    static let signalForInternetStateChange = Signal<Bool,NoError> { (observer) -> Disposable? in
        
        // Set the blocks
        sharedInstanceForInternet!.reachableBlock = {
            (reach: Reachability?) -> Void in
            
            // keep in mind this is called on a background thread
            // and if you are updating the UI it needs to happen
            // on the main thread, like this:
            DispatchQueue.main.async {
                observer.send(value: true)

            }
        }
        
        sharedInstanceForInternet!.unreachableBlock = {
            (reach: Reachability?) -> Void in

            
            DispatchQueue.main.async {

                observer.send(value: false)
            }
        }
        
        sharedInstanceForInternet!.startNotifier()
        
        return nil
    }
    
    //signalProducer for internet state check
    static let signalProducerForInternetStateCheck = SignalProducer<Bool,NSError> { (observer, disposable) in
        
        sharedInstanceForInternet!.isReachable() == true ? observer.send(value: true) : observer.send(value: false)
 
    }
    
    //signal for WIFI state change
    static let signalForWIFIStateChange = Signal<Bool,NoError> { (observer) -> Disposable? in
        
        // Set the blocks
        sharedInstanceForWIFI!.reachableBlock = {
            (reach: Reachability?) -> Void in
            
            // keep in mind this is called on a background thread
            // and if you are updating the UI it needs to happen
            // on the main thread, like this:
            DispatchQueue.main.async {
                observer.send(value: true)
                
            }
        }
        
        sharedInstanceForWIFI!.unreachableBlock = {
            (reach: Reachability?) -> Void in
            
            
            DispatchQueue.main.async {
                
                observer.send(value: false)
            }
        }
        
        sharedInstanceForWIFI!.startNotifier()
        
        return nil
    }
    
    //signalProducer for WIFI state check
    static let signalProducerForWIFIStateCheck = SignalProducer<Bool,NSError> { (observer, disposable) in
        
        sharedInstanceForWIFI!.isReachable() == true ? observer.send(value: true) : observer.send(value: false)
        
    }


    
}
